﻿using Autofac;
using Autofac.Extras.DynamicProxy;
using Superadmin.Net.IService;
using Superadmin.Net.Repository.Base;
using Superadmin.Net.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Superadmin.Net.Extension
{
    public class AutofacModuleRegister : Autofac.Module
    {
        /*
         * 1.看是那个容器起的作用，报错是什么
         * 2.三步走导入autofac容器
         * 3.生命周期，hashcode对比，为什么controller里没变化
         * 4.属性注入
         */
        protected override void Load(ContainerBuilder builder)
        {
            var  basepath = AppContext.BaseDirectory;

            var servicesDllFile = Path.Combine(basepath, "Superadmin.Net.Service.dll");
            var repositoryDllFile = Path.Combine(basepath, "Superadmin.Net.Repository.dll");

            var aopTypes = new List<Type>() { typeof(ServiceAOP) };
            builder.RegisterType<ServiceAOP>();

            builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerDependency();
            builder.RegisterGeneric(typeof(BaseServices<,>)).As(typeof(IBaseServices<,>))
                .InstancePerDependency()
                .EnableInterfaceInterceptors()
                .InterceptedBy(aopTypes.ToArray());

            //获取Service.dll 程序集服务，并注册
            var assemblysServices = Assembly.LoadFrom(servicesDllFile);
            builder.RegisterAssemblyTypes(assemblysServices)
                .AsImplementedInterfaces()
                .InstancePerDependency()
                .PropertiesAutowired()
                .EnableInterfaceInterceptors()
                .InterceptedBy(aopTypes.ToArray());

            //获取Repository.dll 程序集服务，并注册
            var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
            builder.RegisterAssemblyTypes(assemblysRepository)
                .AsImplementedInterfaces()
                .InstancePerDependency()
                .PropertiesAutowired();
        }
    }
}
